import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Between, DataSource, In, Repository } from 'typeorm';
import { UserInfoEntity } from '../../../user/entity/info';
import { OrderOrderEntity } from '../../../order/entity/order';
import { DeviceDeviceEntity } from '../../../device/entity/device';
import { Provide } from '@midwayjs/core';

@Provide()
export class SystemInfo extends BaseService {
  @InjectEntityModel(UserInfoEntity)
  userInfoEntity: Repository<UserInfoEntity>;

  @InjectEntityModel(OrderOrderEntity)
  orderOrderEntity: Repository<OrderOrderEntity>;

  @InjectEntityModel(DeviceDeviceEntity)
  deviceDeviceEntity: Repository<DeviceDeviceEntity>;
  // 获取用户总数
  async info() {
    // return await this.userInfoEntity.count();
    // 用户数量
    const user = await this.userInfoEntity.count();

    // 订单数量
    // 获取状态为1的订单数量
    const order = await this.orderOrderEntity.count({
      where: {
        payStatus: 1,
      },
    });

    // 总设备数
    const device = await this.deviceDeviceEntity.count();

    // 查询在线设备数，deviceStatus = 1
    const onlineDevice = await this.deviceDeviceEntity.count({
      where: {
        deviceStatus: 1,
      },
    });

    // 离线设备数，deviceStatus为0 获取 为2，都是离线
    const offlineDevice = await this.deviceDeviceEntity.count({
      where: {
        deviceStatus: In([0, 2]),
      },
    });

    // 付款总金额
    const payTotal = await this.orderOrderEntity
      .createQueryBuilder()
      .where({ payStatus: 1 })
      .select('SUM(payAmount)', 'total')
      .getRawOne()
      .then(result => result.total || 0);

    //  获取当天的总金额
    const todayTotal = await this.orderOrderEntity
      .createQueryBuilder()
      .where({ payStatus: 1 })
      .andWhere('createTime >= :startTime', {
        // startTime: new Date().setHours(0, 0, 0, 0),
        // 开始时间的格式2025-10-05 02:44:05
        startTime: new Date(new Date().setHours(0, 0, 0, 0)),
      })
      .select('SUM(payAmount)', 'total')
      .getRawOne()
      .then(result => result.total || 0);

    // 今日订单数
    const todayOrderTotal = await this.orderOrderEntity.count({
      where: {
        payStatus: 1,
        createTime: Between(
          new Date(new Date().setHours(0, 0, 0, 0)),
          new Date()
        ),
      },
    });

    return {
      user,
      order,
      payTotal,
      device,
      onlineDevice,
      offlineDevice,
      todayTotal,
      todayOrderTotal,
    };
  }

  // 新增：按商家统计订单金额
  async merchantOrderStatistics(
    page = 1,
    size = 20,
    startTime?: string,
    endTime?: string,
    keyword?: string,
    merchantId?: number
  ) {
    // 对_res进行分组
    // 构建基础查询（角色为商户，且订单为已支付），并按商家聚合
    const buildQB = () => {
      const qb = this.userInfoEntity
        .createQueryBuilder('user_info')
        .select([
          'user_info.id as userId',
          'user_info.nickName as nickName',
          'user_info.phone as phone',
          'SUM(order.payAmount) as totalAmount',
          'COUNT(order.id) as orderCount',
        ])
        // 关联订单表：order_order.deviceBindUserId 对应 user_info.id（商户）
        .innerJoin(
          OrderOrderEntity,
          'order',
          'order.deviceBindUserId = user_info.id'
        )
        // 仅统计商户（role = 2）
        .where('user_info.role = :role', { role: 2 })
        // 仅统计已支付订单
        .andWhere('order.payStatus = :status', { status: 1 })
        .groupBy('user_info.id');

      // 按创建时间筛选（可选）
      if (startTime && endTime) {
        qb.andWhere('order.createTime BETWEEN :startTime AND :endTime', {
          startTime,
          endTime,
        });
      } else if (startTime) {
        qb.andWhere('order.createTime >= :startTime', { startTime });
      } else if (endTime) {
        qb.andWhere('order.createTime <= :endTime', { endTime });
      }

      // 按商户关键字筛选（昵称或手机号，模糊匹配）
      // if (keyword) {
      //   qb.andWhere(
      //     '(user_info.nickName LIKE :kw OR user_info.phone LIKE :kw)',
      //     { kw: `%${keyword}%` }
      //   );
      // }

      // 按商户ID精确筛选
      if (merchantId) {
        qb.andWhere('user_info.id = :merchantId', { merchantId });
      }

      return qb;
    };

    // 计算总数（聚合后的商家数量）
    const total = (await buildQB().getRawMany()).length;

    // 分页列表
    const list = await buildQB()
      .orderBy('totalAmount', 'DESC')
      .skip((page - 1) * size)
      .take(size)
      .getRawMany();

    // 为每个商户查询其拥有的设备列表
    const listWithDevices = await Promise.all(
      list.map(async merchant => {
        // 查询该商户拥有的所有设备
        const devices = await this.deviceDeviceEntity.find({
          where: { userId: merchant.userId },
          select: ['id', 'deviceNo', 'deviceStatus', 'lastOnlineTime'],
        });

        // 统计设备状态
        const deviceStats = {
          total: devices.length,
          online: devices.filter(d => d.deviceStatus === 1).length,
          offline: devices.filter(
            d => d.deviceStatus === 0 || d.deviceStatus === 2
          ).length,
        };

        return {
          ...merchant,
          devices,
          deviceStats,
        };
      })
    );

    return {
      list: listWithDevices,
      pagination: {
        page,
        size,
        total,
      },
    };
  }

  // 代理订单统计
  async agentOrderStatistics(
    page = 1,
    size = 20,
    startTime?: string,
    endTime?: string,
    keyword?: string,
    merchantId?: number
  ) {
    // 对_res进行分组
    // 构建基础查询（角色为商户，且订单为已支付），并按商家聚合
    const buildQB = () => {
      const qb = this.userInfoEntity
        .createQueryBuilder('user_info')
        .select([
          'user_info.id as userId',
          'user_info.nickName as nickName',
          'user_info.phone as phone',
          'SUM(order.payAmount) as totalAmount',
          'COUNT(order.id) as orderCount',
        ])
        // 关联订单表：order_order.deviceBindUserId 对应 user_info.id（商户）
        .innerJoin(
          OrderOrderEntity,
          'order',
          'order.deviceBindAgentId = user_info.id'
        )
        // 仅统计商户（role = 2）
        .where('user_info.role = :role', { role: 1 })
        // 仅统计已支付订单
        .andWhere('order.payStatus = :status', { status: 1 })
        .groupBy('user_info.id');

      // 按创建时间筛选（可选）
      if (startTime && endTime) {
        qb.andWhere('order.createTime BETWEEN :startTime AND :endTime', {
          startTime,
          endTime,
        });
      } else if (startTime) {
        qb.andWhere('order.createTime >= :startTime', { startTime });
      } else if (endTime) {
        qb.andWhere('order.createTime <= :endTime', { endTime });
      }

      // 按商户关键字筛选（针对订单归属的商户信息）
      // if (keyword) {
      //   qb.andWhere(
      //     '(user_info.nickName LIKE :kw OR user_info.phone LIKE :kw)',
      //     { kw: `%${keyword}%` }
      //   );
      // }

      // 在代理统计中按商户ID筛选订单归属商户
      // if (merchantId) {
      //   qb.andWhere('order.deviceBindUserId = :merchantId', { merchantId });
      // }
      // 按商户ID精确筛选
      if (merchantId) {
        qb.andWhere('user_info.id = :merchantId', { merchantId });
      }

      return qb;
    };

    // 计算总数（聚合后的商家数量）
    const total = (await buildQB().getRawMany()).length;

    // 分页列表
    const list = await buildQB()
      .orderBy('totalAmount', 'DESC')
      .skip((page - 1) * size)
      .take(size)
      .getRawMany();

    // 为每个商户查询其拥有的设备列表
    const listWithDevices = await Promise.all(
      list.map(async merchant => {
        // 查询该商户拥有的所有设备
        const devices = await this.deviceDeviceEntity.find({
          where: { agentId: merchant.userId },
          select: ['id', 'deviceNo', 'deviceStatus', 'lastOnlineTime'],
        });

        // 统计设备状态
        const deviceStats = {
          total: devices.length,
          online: devices.filter(d => d.deviceStatus === 1).length,
          offline: devices.filter(
            d => d.deviceStatus === 0 || d.deviceStatus === 2
          ).length,
        };

        return {
          ...merchant,
          devices,
          deviceStats,
        };
      })
    );

    return {
      list: listWithDevices,
      pagination: {
        page,
        size,
        total,
      },
    };
  }
}
